#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>  // 正确的头文件
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>  // 为了使用 strerror
#include <pthread.h>
#include <stdlib.h>
 
#define N 64
void* handler_thread(void* arg){
    
    int ret=-1;
    int clientfd=(* ( (int*)arg ) );
    free(arg);
    arg=NULL;
    char buf[N] = {0};
    while (1){
        ret = recv(clientfd, buf, N, 0);
        if (ret < 0)
        {
            perror("recv err");
            continue;
        }
        else if (ret == 0)
        {
            printf("peer exit\n");
            break;
        }
        else
        {
            printf("%s\n",buf);
            // inet_ntoa(cliaddr.sin_addr), ntohs(cliaddr.sin_port), buf);
        }
    }
    close(clientfd);
    
    pthread_exit(NULL);
}
 
int main(int argc, char const *argv[])
{
 
    // if (argc < 3)
    // {
    //     printf("usage: %s <ip> <port>\n", argv[0]);
    //     return -1;
    // }
 
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        perror("socket err");
        return -1;
    }
 
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8080);
    // 自动绑定所有的本机网卡的地址
    addr.sin_addr.s_addr = INADDR_ANY;  // 或者使用 inet_addr(argv[1]) 来绑定特定 IP
 
    int addrlen = sizeof(addr);
 
    if (bind(sockfd, (struct sockaddr *)&addr, addrlen) < 0)
    {
        perror("bind err");
        close(sockfd);
        return -1;
    }
 
    if (listen(sockfd, 5) < 0)
    {
        perror("listen err");
        close(sockfd);
        return -1;
    }
 
    printf("wait client connect\n");
    int clifd =-1;
    struct sockaddr_in cliaddr;
 

    pthread_t tid=-1;
    int i=0;
    
    while (1)
    {   
        clifd = accept(sockfd, (struct sockaddr *)&cliaddr, &addrlen);
        if (clifd < 0)
        {
            perror("accept err");
            continue;
        }else{
            int* new_sock=(int*)malloc(sizeof(int));
            if(new_sock == NULL){
                perror("malloc err");
                close(clifd);
                break;
            }
            *new_sock=clifd;
            if(pthread_create(&tid,NULL,handler_thread,(void*)new_sock) != 0){
                perror("pthread_create err");
                // close(sockfd);
                close(clifd);
                continue;
            }
            if(pthread_detach(tid) != 0){
                perror("pthread_detach err");
                // close(sockfd);
                close(clifd);
                pthread_join(tid,NULL);
                continue;
            }
            // pthread_detach(tid);
        }
        i++;
        printf("第%d个\n",i);
    }
 
    close(sockfd);
    close(clifd);
 
    return 0;
}